//
//  GroupAddViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-17.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GroupAddViewController.h"
#import "StringUtil.h"
#import "FriendGroup.h"
#import "TwitterClient.h"
#import "GuaziAppDelegate.h"
#import "FriendsViewController.h"
#import "GroupService.h"

@interface GroupAddViewController(private)
- (void) buildBarItems;
- (void) refreshContactsView:(FriendGroup*)group add:(BOOL)isAdd;
@end



@implementation GroupAddViewController

@synthesize groupName;
@synthesize isPublic;
@synthesize group;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	[self buildBarItems];
	[self.groupName becomeFirstResponder];
	
	if ( group && group.groupId > 0 ) {
		self.groupName.text = group.name;
		self.isPublic.on = group.isPublic;
        self.navigationItem.title = group.name;
	}
    else {
        self.navigationItem.title = @"新建分组";
    }
}


- (void) buildBarItems
{
    if ( self.navigationItem.rightBarButtonItem == nil ) {
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"保存" 
                                                                                   style:UIBarButtonItemStylePlain 
                                                                                  target:self action:@selector(save)] autorelease];
    }
}


- (void) save
{
	NSString* name = [groupName.text trim];
	if ( [name length] == 0 ) {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"错误" 
														message:@"请输入组名称" 
													   delegate:nil 
											  cancelButtonTitle:@"确定" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}
	
	BOOL result = NO;
	if ( group && group.groupId > 0 ) {
		group.name = name;
		group.isPublic = isPublic.on;
        result = [GroupService editGroup:group];
        if ( result ) {
            [self refreshContactsView:group add:NO];
        }
	}
	else {
		FriendGroup* g = [[FriendGroup alloc] init];
		g.name = name;
		g.isPublic = isPublic.on;
        g.friendCount = 0;
        g.userId = [GuaziAppDelegate getAppDelegate].user.userId;
        g.createdAt = (time_t) [[NSDate date] timeIntervalSince1970];
        g.friends = [NSMutableArray arrayWithCapacity:0];
        
        result = [GroupService addGroup:g];
        if ( result ) {
            [self refreshContactsView:g add:YES];
        }
		[g release];
	}
	
	if ( !result ) {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"错误" 
														message:@"保存组信息失败" 
													   delegate:nil 
											  cancelButtonTitle:@"确定" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	
    if ( [GuaziAppDelegate getAppDelegate].selectedTab == 0 ) {
        FriendsViewController* controller = [[GuaziAppDelegate getAppDelegate] friendsViewController];
        [controller refreshTableView];
    }
}


- (void) dismiss 
{
    [[[GuaziAppDelegate getAppDelegate] currentNavigationController] dismissModalViewControllerAnimated:YES];
}


- (void) saveInModelView
{
    [self save];
    [[[GuaziAppDelegate getAppDelegate] currentNavigationController] dismissModalViewControllerAnimated:YES];
}


- (void) saveInStackView
{
    [self save];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void) refreshContactsView:(FriendGroup*)agroup add:(BOOL)isAdd
{
    FriendsViewController* controller = [[GuaziAppDelegate getAppDelegate] friendsViewController];
    if ( isAdd ) {
        [controller refreshAddGroup:agroup];
    }
    else {
        [controller refreshGroup:agroup];
    }
}



/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
	self.groupName = nil;
	self.isPublic = nil;
	self.group = nil;
}


- (void)dealloc {
	[groupName release];
	[isPublic release];
	[group release];
    [super dealloc];
}


@end
